package yiran.onemonthcard;

import org.bukkit.plugin.java.JavaPlugin;
import yiran.onemonthcard.command.OneMonthCardCommand;
import yiran.onemonthcard.eventhandler.PlayerJoinListener;
import yiran.onemonthcard.eventhandler.PlayerQuitListener;
import yiran.onemonthcard.lang.LangHelper;
import yiran.onemonthcard.output.Logger;
import yiran.onemonthcard.system.OneMonthCardSystem;

public final class OneMonthCard extends JavaPlugin {
    private OneMonthCardSystem onemonthcardsystem;

    @Override
    public void onEnable() {
        try {
            Class.forName("org.sqlite.JDBC"); // 确保驱动可用
        } catch (ClassNotFoundException e) {
            getLogger().severe("SQLite JDBC 驱动未找到！");
            setEnabled(false);
            return;
        }

        // 初始化日志系统
        Logger.init(this);

        // 确保插件数据目录存在
        if (!getDataFolder().exists()) {
            boolean created = getDataFolder().mkdirs();
            if (!created) {
                getLogger().severe("无法创建插件数据目录!");
                setEnabled(false);
                return;
            }
        }

        try {
            // 先保存默认配置
            saveDefaultConfig();

            // 检查配置文件是否真正加载
            reloadConfig();
            if (getConfig() == null) {
                throw new IllegalStateException("配置文件加载失败");
            }

            int duration = getConfig().getInt("duration", 30); // 默认30天
            getLogger().info("配置加载成功，设置的月卡天数为: " + duration);

        } catch (Exception e) {
            getLogger().severe("加载配置失败，使用默认值30天: " + e.getMessage());
        }

        LangHelper.init(this);

        try {
            onemonthcardsystem = new OneMonthCardSystem(this);
            // 修改：加载所有玩家数据（不只是在线玩家）
            onemonthcardsystem.loadAllPlayerData();
        } catch (Exception e) {
            getLogger().severe("月卡系统初始化失败: " + e.getMessage());
            setEnabled(false);
            return;
        }

        // 注册命令,事件和Tab补全器
        if (getCommand("onemonthcard") != null) {
            OneMonthCardCommand commandExecutor = new OneMonthCardCommand(onemonthcardsystem, this);
            getCommand("onemonthcard").setExecutor(commandExecutor);
            getCommand("onemonthcard").setTabCompleter(commandExecutor);
        } else {
            getLogger().severe("无法注册命令'onemonthcard'，请检查plugin.yml!");
            setEnabled(false);
            return;
        }

        getServer().getPluginManager().registerEvents(new PlayerQuitListener(onemonthcardsystem), this);
        getServer().getPluginManager().registerEvents(new PlayerJoinListener(onemonthcardsystem), this);

        // 设置定时任务
        setupTasks();

        Logger.printBanner();
        Logger.info("月卡插件已启动");
    }

    @Override
    public void onDisable() {
        if (onemonthcardsystem != null) {
            onemonthcardsystem.savePlayerData();
            onemonthcardsystem.closeDatabase();
        }
        Logger.error("月卡插件已关闭");
    }

    private void setupTasks() {
        // 修改为每天检查一次过期状态
        long dailyTicks = 20L * 60 * 60 * 24;
        getServer().getScheduler().runTaskTimer(
                this,
                onemonthcardsystem::checkExpiredCards,
                0L,
                dailyTicks
        );
    }

    public String getMessage(String key) {
        return LangHelper.getString(key);
    }
}
